package datamining.sequence;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

import datamining.common.Cloneable;

/**
 * @author xujinghu
 *
 * @param <ItemType>
 */
public class ItemSet<ItemType> implements Cloneable<ItemSet<ItemType>>, Comparable<ItemSet<ItemType>> {
	private Set<ItemType> items = new TreeSet<ItemType>();
	public int idx;

	public ItemSet() {
		super();
	}

	public ItemSet(Set<ItemType> items) {
		super();
		this.items = items;
	}

	@Override
	public int compareTo(ItemSet<ItemType> o) {
		Iterator<ItemType> thisIter = items.iterator();
		Iterator<ItemType> anotherIter = o.getItems().iterator();

		while (thisIter.hasNext()) {
			if (!anotherIter.hasNext()) {
				return 1;
			}

			ItemType i1 = thisIter.next();
			ItemType i2 = anotherIter.next();

			int diff = ((Comparable)i1).compareTo(i2);
			if (diff != 0) {
				return diff;
			}
		}

		if (items.size() < o.getItems().size()) {
			return -1;
		}

		return 0;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		@SuppressWarnings("unchecked")
		ItemSet<ItemType> other = (ItemSet<ItemType>) obj;
		if (items == null) {
			if (other.items != null)
				return false;
		} else if (!items.equals(other.items))
			return false;
		return true;
	}

	public Set<ItemType> getItems() {
		return items;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((items == null) ? 0 : items.hashCode());
		return result;
	}

	public void setItems(Set<ItemType> items) {
		if (items == null) {
			this.items = new TreeSet<ItemType>();
		} else {
			this.items = items;
		}
	}

	public void add(ItemType item) {
		items.add(item);
	}

	@Override
	public String toString() {
		String itemSet_str = "";
		for(ItemType item : items)
			itemSet_str += item;
		return itemSet_str;
	}
	
	public ItemSet<ItemType> clone(){
		ItemSet<ItemType> copy = new ItemSet<ItemType>();
		
		for(ItemType item : items){
			copy.getItems().add(item);
		}
		
		return copy;
	}
}
